<?php
namespace backend\controllers;

use common\models\User;
use common\util\Helper;
use common\util\MessageCode;
use Yii;
use yii\rest\Controller;
use yii\web\BadRequestHttpException;

/**
 * Public controller
 */
class PublicController extends Controller
{
    /**
     * 用户注册.
     *
     * @return mixed
     * @throws \yii\base\Exception
     */
    public function actionRegister()
    {
        $mobile     = Yii::$app->request->body('mobile');
        $email      = Yii::$app->request->body('email');
        $password   = Yii::$app->request->body('password');
        $repassword = Yii::$app->request->body('repassword');
        $code       = Yii::$app->request->body('code');

        if (!(new MessageCode())->validateMessageCodeByMobile($mobile, $code)) {
            throw new BadRequestHttpException("验证码不正确");
        }

        $user        = new User();
        $user->phone = $mobile;
        $user->email = $email;
        // 暂定手机号作为用户名.
        $user->username   = $mobile;
        $user->password   = $password;
        $user->repassword = $repassword;

        $user->setPassword($password);
        $user->generateAuthKey();

        if (!$user->save()) {
            throw new BadRequestHttpException(current($user->firstErrors));
        }

        return true;
    }

    /**
     * 登录.
     *
     * @throws \Exception
     */
    public function actionLogin()
    {
        // 这里的username就是登录用户的email或者mobile.
        $mobileOrEmail = Yii::$app->request->getRawBodyAsObject('username');
        $password      = Yii::$app->request->getRawBodyAsObject('password');
        if (!($user = User::find()
            ->where(['or', ['phone' => $mobileOrEmail], ['email' => $mobileOrEmail]])
            ->andWhere(['status' => User::STATUS_ACTIVE])
            ->one())
        ) {
            throw new BadRequestHttpException("用户名错误");
        }
        /** @var $user User */
        if (!$user->validatePassword($password)) {
            throw new BadRequestHttpException('密码错误!');
        }

        if (Yii::$app->user->login($user)) {
            $session = \Yii::$app->session;
            $session->open();
            $session[User::USER_SESSION_ID] = \Yii::$app->user->identity->id;

            return [
                'token' => $session->id,
            ];
        } else {
            throw new BadRequestHttpException("登陆失败");
        }
    }

    /**
     * 发送验证码.
     *
     * @throws \Exception
     */
    public function actionSendCode()
    {
        $mobile = \Yii::$app->request->body("mobile");
        // 判断手机号是否正确.
        if (!Helper::checkMobile($mobile)) {
            throw new BadRequestHttpException("手机号不正确");
        }

        $code = (new MessageCode())->genMessageCode($mobile);
        return true;
    }

    /**
     * 获取校验验证码.
     *
     * @throws \Exception
     */
    public function actionGetMessageCode()
    {
        $mobile = \Yii::$app->request->body("mobile");
        // 判断手机号是否正确.
        if (!Helper::checkMobile($mobile)) {
            throw new BadRequestHttpException("手机号不正确");
        }

        $code = (new MessageCode())->getMessageCodeByMobile($mobile);

        if (!$code) {
            throw new BadRequestHttpException("验证码不存在");
        }

        return $code;
    }
}
